package com.example.demo1.controller;

import com.example.demo1.pojo.Result;
import com.example.demo1.pojo.User;
import com.example.demo1.service.CategoryService;
import com.example.demo1.service.UserService;
import com.example.demo1.service.impl.CategoryServiceImpl;
import com.example.demo1.utils.JwtUtil;
import com.example.demo1.utils.Md5Util;
import com.example.demo1.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CategoryServiceImpl categoryServiceImpl;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {

        //查询用户
        User u = userService.findUserName(username);
        if (u == null) {
            //没有占用
            //注册
            userService.register(username, password);
            return Result.success();
        } else {
            //占用
            return Result.error("用户名已被占用");
        }
    }

    //登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //
        User user = userService.findUserName(username);

        //判断用户是否存在
        if (user == null) {
            return Result.error("用户名不存在");
        }

        //判断密码是否正确
        if (user.getPassword().equals(Md5Util.getMD5String(password))) {

            //登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);

            //把token令牌存储到redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);

            return Result.success(token);

        }
        return Result.error("密码错误");

    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //根据用户名查询用户
        Map<String,Object> map = ThreadLocalUtil.get();
        /*Map<String, Object> map = JwtUtil.parseToken(token);*/
        String username = (String) map.get("username");
        User user = userService.findUserName(username);
        return Result.success(user);
    }

    //
    @PutMapping("/update")
    //判断传的参数是否符合

    public Result update(@RequestBody @Validated User user) {
        userService.update();
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        //调用service层的方法
        userService.updateAvatar(avatarUrl);
        //返回成功信息
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> param,@RequestHeader("Authorization") String token){

        //参数校验
        String old_pwd = param.get("old_pwd");
        String new_pwd = param.get("new_pwd");
        String re_pwd = param.get("re_pwd");

        if(!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要参数");
        }
        //判断原先密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findUserName(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(old_pwd))){
            return Result.error("原密码不正确");
        }
        //判断两次填写的密码是否一样
        if(!new_pwd.equals(re_pwd)){
            return Result.error("两次填写密码不一致");
        }

        //调用service中的方法修改密码
        userService.updatePwd(new_pwd);

        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id){
        CategoryService.deleteById(id);
        return Result.success();
    }

}
